package cn.elves.model.activity.service.impl;

import cn.elves.model.activity.entity.po.Activity;
import cn.elves.model.activity.entity.po.UserTakeActivityCount;
import cn.elves.model.activity.mapper.UserTakeActivityCountMapper;
import cn.elves.model.activity.service.ActivityService;
import cn.elves.model.activity.service.UserTakeActivityCountService;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import javax.annotation.Resource;
import java.util.List;

/**
 * @author pc
 * @description 针对表【user_take_activity_count】的数据库操作Service实现
 * @createDate 2024-06-17 00:09:05
 */
@Service
public class UserTakeActivityCountServiceImpl extends ServiceImpl<UserTakeActivityCountMapper, UserTakeActivityCount>
        implements UserTakeActivityCountService {

    @Resource
    private UserTakeActivityCountMapper userTakeActivityCountMapper;

    @Resource
    private ActivityService activityService;

    @Override
    public UserTakeActivityCount selectActivityTakeCount(Long userId, Long activityId) {
        QueryWrapper<UserTakeActivityCount> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("user_id", userId);
        queryWrapper.eq("activityId", activityId);
        queryWrapper.orderByDesc("id");
        List<UserTakeActivityCount> userTakeActivityCounts = userTakeActivityCountMapper.selectList(queryWrapper);
        if (CollectionUtils.isEmpty(userTakeActivityCounts)) {
            return null;
        }
        return userTakeActivityCounts.get(0);
    }

    @Override
    public UserTakeActivityCount createUserTakeActivityCount(Long userId, Long activityId) {
        Activity activity = activityService.getById(activityId);
        UserTakeActivityCount userTakeActivityCount = new UserTakeActivityCount();
        userTakeActivityCount.setActivityId(activityId);
        userTakeActivityCount.setUserId(userId.toString());
        userTakeActivityCount.setTotalCount(activity.getTakeCount());
        userTakeActivityCount.setLeftCount(activity.getTakeCount());
        userTakeActivityCountMapper.insert(userTakeActivityCount);
        return userTakeActivityCount;
    }

    @Override
    public Boolean increaseLeftCount(UserTakeActivityCount userTakeActivityCount) {
        Integer count = userTakeActivityCountMapper.increaseLeftCount(userTakeActivityCount.getId());
        return count != 0;
    }
}




